﻿// Copyright 2007-2009 Stuart Caborn, Alex Scordellis
//  
//  Licensed under the Apache License, Version 2.0 (the "License"); 
//  http://www.apache.org/licenses/LICENSE-2.0

using System;
using System.Collections.Generic;

namespace NSynthesis
{
    public static class Helpers
    {
        public static void EachWithIndex<TSource>(this IEnumerable<TSource> input, Action<TSource, int> action)
        {
            var i = 0;
            foreach (var t in input)
            {
                action(t, i++);
            }
        }
        
        public static IEnumerable<TRet> EachWithIndex<TSource, TRet>(this IEnumerable<TSource> input, Func<TSource, int, TRet> action)
        {
            var i = 0;
            foreach (var t in input)
            {
                yield return action(t, i++);
            }
        }

        public static void Zip<TSource>(this IEnumerable<TSource> input, IEnumerable<TSource> other, Action<TSource, TSource> action)
        {
            var enumerator = other.GetEnumerator();
            foreach (var t in input)
            {
                if (!enumerator.MoveNext())
                    throw new ArgumentException("This enumerable had more entries than the other one.");
                action(t, enumerator.Current);
            }
            if (enumerator.MoveNext())
                throw new ArgumentException("Other enumerable had more entries than this one.");
        }

        public static IEnumerable<TRet> Zip<TSource, TRet>(this IEnumerable<TSource> input, IEnumerable<TSource> other, Func<TSource, TSource, TRet> action)
        {
            var enumerator = other.GetEnumerator();
            foreach (var t in input)
            {
                if (!enumerator.MoveNext())
                    throw new ArgumentException("This enumerable had more entries than the other one.");
                yield return action(t, enumerator.Current);
            }
            if (enumerator.MoveNext())
                throw new ArgumentException("Other enumerable had more entries than this one.");
        }

        public static bool All(this IEnumerable<bool> input)
        {
            foreach (var b in input)
                if (!b)
                    return false;
            return true;
        }
    }
}